<template>
  <q-layout view="hHh Lpr lFf">
    <!-- 顶部导航栏 -->
    <q-header elevated class="bg-primary text-white">
      <q-toolbar>
        <q-btn
          flat
          dense
          round
          icon="menu"
          aria-label="Menu"
          @click="toggleLeftDrawer"
        />

        <q-toolbar-title class="text-weight-bold"> 网盘 </q-toolbar-title>

        <!-- 搜索栏 -->
        <q-input
          dark
          dense
          standout
          v-model="searchText"
          input-class="text-right"
          class="q-ml-md"
          placeholder="搜索文件和目录..."
          @keyup.enter="performSearch"
        >
          <template v-slot:append>
            <q-icon
              name="search"
              @click="performSearch"
              style="cursor: pointer"
            />
          </template>
        </q-input>

        <!-- 右侧工具栏 -->
        <div class="row items-center q-gutter-sm">
          <q-btn flat round icon="person" @click="goToProfile" />
        </div>
      </q-toolbar>
    </q-header>

    <!-- 左侧边栏 -->
    <q-drawer
      v-model="leftDrawerOpen"
      show-if-above
      bordered
      class="bg-grey-1"
      :width="280"
    >
      <q-list padding>
        <!-- 文件分类 -->
        <q-item-label header class="text-weight-bold"> 文件分类 </q-item-label>

        <q-item clickable v-ripple @click="goToHome">
          <q-item-section avatar>
            <q-icon name="folder" color="primary" />
          </q-item-section>
          <q-item-section>我的网盘</q-item-section>
        </q-item>

        <q-item clickable v-ripple @click="goToCategory('video')">
          <q-item-section avatar>
            <q-icon name="videocam" color="red" />
          </q-item-section>
          <q-item-section>视频</q-item-section>
        </q-item>

        <q-item clickable v-ripple @click="goToCategory('image')">
          <q-item-section avatar>
            <q-icon name="image" color="green" />
          </q-item-section>
          <q-item-section>图片</q-item-section>
        </q-item>

        <q-item clickable v-ripple @click="goToCategory('music')">
          <q-item-section avatar>
            <q-icon name="music_note" color="orange" />
          </q-item-section>
          <q-item-section>音乐</q-item-section>
        </q-item>

        <q-item clickable v-ripple @click="goToCategory('document')">
          <q-item-section avatar>
            <q-icon name="description" color="blue" />
          </q-item-section>
          <q-item-section>文档</q-item-section>
        </q-item>

        <!-- <q-item clickable v-ripple @click="handleItemClick">
          <q-item-section avatar>
            <q-icon name="add" color="grey" />
          </q-item-section>
          <q-item-section>添加标签...</q-item-section>
        </q-item> -->

        <q-separator class="q-my-md" />

        <!-- 其他功能 -->
        <!-- <q-item clickable v-ripple @click="handleItemClick">
          <q-item-section avatar>
            <q-icon name="share" color="purple" />
          </q-item-section>
          <q-item-section>我的分享</q-item-section>
        </q-item> -->

        <q-item clickable v-ripple @click="handleOfflineDownload">
          <q-item-section avatar>
            <q-icon name="download" color="teal" />
          </q-item-section>
          <q-item-section>离线下载</q-item-section>
        </q-item>

        <!-- <q-item clickable v-ripple @click="handleItemClick">
          <q-item-section avatar>
            <q-icon name="link" color="indigo" />
          </q-item-section>
          <q-item-section>连接</q-item-section>
        </q-item> -->

        <q-item clickable v-ripple @click="showTaskDialog = true">
          <q-item-section avatar>
            <q-icon name="queue" color="brown" />
          </q-item-section>
          <q-item-section>任务队列</q-item-section>
        </q-item>

        <q-separator class="q-my-md" />

        <!-- 存储空间 -->
        <!-- <q-item>
          <q-item-section avatar>
            <q-icon name="bar_chart" color="deep-orange" />
          </q-item-section>
          <q-item-section>
            <q-item-label>使用情况</q-item-label>
            <q-linear-progress
              :value="rootSize / (1024 * 1024 * 1024 * 50)"
              color="primary"
              class="q-mt-sm"
            />
            <q-item-label caption class="q-mt-xs">
              {{ formatSize(rootSize) }} / 5GB ({{ rootCount }} 个资源)
            </q-item-label>
          </q-item-section>
        </q-item> -->
      </q-list>
    </q-drawer>

    <!-- 主内容区域 -->
    <q-page-container>
      <router-view
        :directory-data="directoryData"
        @update-current-path="updateCurrentPath"
        @offline-download="handleOfflineDownload"
      />

      <!-- 任务管理浮动按钮 -->
      <q-page-sticky position="bottom-right" :offset="[18, 18]">
        <q-btn
          fab
          icon="queue"
          color="primary"
          size="lg"
          @click="showTaskDialog = true"
        />
        <q-badge
          v-if="activeTaskCount > 0"
          color="red"
          floating
          class="q-mt-sm q-mr-sm"
        >
          {{ activeTaskCount }}
        </q-badge>
      </q-page-sticky>
    </q-page-container>

    <!-- 登录对话框 -->
    <q-dialog v-model="showLoginDialog" persistent>
      <q-card style="min-width: 350px">
        <q-card-section class="row items-center q-pb-none">
          <div class="text-h6">需要登录</div>
          <q-space />
        </q-card-section>

        <q-card-section class="q-pt-none">
          <p>请先登录后才能使用此功能。</p>
        </q-card-section>

        <q-card-actions align="right" class="text-primary">
          <q-btn flat label="去登录" @click="goToLogin" />
        </q-card-actions>
      </q-card>
    </q-dialog>

    <!-- 离线下载对话框 -->
    <q-dialog v-model="showOfflineDownloadDialog" persistent>
      <q-card style="min-width: 500px">
        <q-card-section class="row items-center q-pb-none">
          <div class="text-h6">离线下载</div>
          <q-space />
          <q-btn icon="close" flat round dense v-close-popup />
        </q-card-section>

        <q-card-section class="q-pt-md">
          <q-form @submit="submitOfflineDownload" class="q-gutter-md">
            <q-input
              v-model="offlineDownloadForm.url"
              label="文件URL"
              placeholder="请输入完整的文件URL"
              outlined
              :rules="[(val) => !!val || '请输入URL']"
              required
            />

            <q-input
              v-model="offlineDownloadForm.filename"
              label="文件名（可选）"
              placeholder="请输入保存的文件名，留空将自动从URL提取"
              outlined
            />

            <q-select
              v-model="offlineDownloadForm.path"
              :options="directoryOptions"
              label="保存目录"
              outlined
              option-label="label"
              option-value="value"
              emit-value
              map-options
            >
              <template v-slot:option="scope">
                <q-item v-bind="scope.itemProps">
                  <q-item-section avatar>
                    <q-icon name="folder" color="primary" />
                  </q-item-section>
                  <q-item-section>
                    <q-item-label>{{ scope.opt.label }}</q-item-label>
                    <q-item-label caption>{{ scope.opt.value }}</q-item-label>
                  </q-item-section>
                </q-item>
              </template>
            </q-select>
          </q-form>
        </q-card-section>

        <q-card-actions align="right" class="text-primary">
          <q-btn flat label="取消" v-close-popup />
          <q-btn
            unelevated
            label="开始下载"
            color="primary"
            @click="submitOfflineDownload"
            :loading="submittingOfflineDownload"
          />
        </q-card-actions>
      </q-card>
    </q-dialog>

    <!-- 任务管理对话框 -->
    <q-dialog v-model="showTaskDialog">
      <q-card class="task-dialog">
        <q-card-section class="row items-center q-pb-none">
          <div class="text-h6">任务管理</div>
          <q-space />
          <q-btn icon="close" flat round dense v-close-popup />
        </q-card-section>

        <q-card-section class="q-pt-md">
          <!-- 任务统计 -->
          <div class="row q-gutter-md q-mb-lg">
            <q-card class="stat-card" flat bordered>
              <q-card-section class="text-center">
                <div class="text-h4 text-primary">{{ taskStats.total }}</div>
                <div class="text-caption">总任务数</div>
              </q-card-section>
            </q-card>
            <q-card class="stat-card" flat bordered>
              <q-card-section class="text-center">
                <div class="text-h4 text-orange">{{ taskStats.running }}</div>
                <div class="text-caption">运行中</div>
              </q-card-section>
            </q-card>
            <q-card class="stat-card" flat bordered>
              <q-card-section class="text-center">
                <div class="text-h4 text-green">{{ taskStats.completed }}</div>
                <div class="text-caption">已完成</div>
              </q-card-section>
            </q-card>
            <q-card class="stat-card" flat bordered>
              <q-card-section class="text-center">
                <div class="text-h4 text-red">{{ taskStats.failed }}</div>
                <div class="text-caption">失败</div>
              </q-card-section>
            </q-card>
          </div>

          <!-- 文件拖拽上传区域 -->
          <div
            class="upload-drop-zone q-pa-lg text-center"
            :class="{ 'drag-over': isDragOver }"
            @drop="handleFileDrop"
            @dragover.prevent="isDragOver = true"
            @dragleave.prevent="isDragOver = false"
            @dragenter.prevent
          >
            <q-icon name="cloud_upload" size="48px" color="grey-4" />
            <div class="text-h6 text-grey-6 q-mt-md">拖拽文件到此处上传</div>
            <div class="text-caption text-grey-5">支持单个或多个文件</div>
          </div>

          <!-- 任务列表 -->
          <div class="q-mt-lg">
            <div class="row items-center justify-between q-mb-md">
              <h6 class="q-ma-none">任务列表</h6>
              <div class="row q-gutter-sm">
                <q-btn
                  flat
                  round
                  icon="refresh"
                  @click="refreshTasks"
                  :loading="refreshingTasks"
                />
                <q-btn
                  flat
                  round
                  icon="clear_all"
                  @click="clearCompletedTasks"
                  :disable="
                    taskStats.completed +
                      taskStats.failed +
                      taskStats.cancelled ===
                    0
                  "
                />
              </div>
            </div>

            <q-list bordered separator>
              <q-item v-for="task in allTasks" :key="task.id" class="task-item">
                <q-item-section avatar>
                  <q-icon
                    :name="getTaskIcon(task.type)"
                    :color="getTaskColor(task.status)"
                    size="24px"
                  />
                </q-item-section>

                <q-item-section>
                  <q-item-label class="text-weight-medium">
                    {{ getTaskTitle(task) }}
                  </q-item-label>
                  <q-item-label caption>
                    {{ getTaskDescription(task) }}
                  </q-item-label>

                  <!-- 进度条 -->
                  <q-linear-progress
                    v-if="task.status === 'running' || task.status === 'paused'"
                    :value="task.progress / 100"
                    :color="task.status === 'paused' ? 'orange' : 'primary'"
                    class="q-mt-sm"
                  />

                  <div class="text-caption text-grey-6 q-mt-xs">
                    {{ formatTime(task.createdAt) }} |
                    {{ getStatusText(task.status) }}
                    <span v-if="task.retryCount > 0">
                      | 重试 {{ task.retryCount }}/{{ task.maxRetries }}</span
                    >
                  </div>
                </q-item-section>

                <q-item-section side>
                  <div class="row q-gutter-xs">
                    <!-- 暂停/恢复按钮 -->
                    <q-btn
                      v-if="task.status === 'running'"
                      flat
                      round
                      dense
                      icon="pause"
                      @click="pauseTask(task.id)"
                    />
                    <q-btn
                      v-if="task.status === 'paused'"
                      flat
                      round
                      dense
                      icon="play_arrow"
                      @click="resumeTask(task.id)"
                    />

                    <!-- 重试按钮 -->
                    <q-btn
                      v-if="task.status === 'failed'"
                      flat
                      round
                      dense
                      icon="refresh"
                      @click="retryTask(task.id)"
                    />

                    <!-- 取消按钮 -->
                    <q-btn
                      v-if="
                        task.status === 'pending' || task.status === 'running'
                      "
                      flat
                      round
                      dense
                      icon="close"
                      @click="cancelTask(task.id)"
                    />

                    <!-- 删除按钮 -->
                    <q-btn
                      v-if="
                        task.status === 'completed' ||
                        task.status === 'failed' ||
                        task.status === 'cancelled'
                      "
                      flat
                      round
                      dense
                      icon="delete"
                      @click="removeTask(task.id)"
                    />
                  </div>
                </q-item-section>
              </q-item>

              <!-- 空状态 -->
              <q-item v-if="allTasks.length === 0">
                <q-item-section class="text-center q-pa-lg">
                  <q-icon name="queue" size="48px" color="grey-4" />
                  <div class="text-h6 text-grey-6 q-mt-md">暂无任务</div>
                  <div class="text-caption text-grey-5">
                    拖拽文件到上方区域开始上传
                  </div>
                </q-item-section>
              </q-item>
            </q-list>
          </div>
        </q-card-section>
      </q-card>
    </q-dialog>
  </q-layout>
</template>

<script setup>
import { ref, onMounted, watch, computed } from "vue";
import { onLoggedIn, isLogin, Dialog, handleLoginStatus } from "src/js/common";
import { useQuasar } from "quasar";
import { useRouter } from "vue-router";
import { browseDirectory } from "src/js/cloudApi";
import taskQueue, { TaskType, TaskStatus } from "src/js/taskQueue";

defineOptions({
  name: "MainLayout",
});

const $q = useQuasar();
const router = useRouter();
const leftDrawerOpen = ref(true);
const searchText = ref("");
const showLoginDialog = ref(true);
const showUserMenu = ref(false);
const directoryData = ref(null);
const rootSize = ref(0);
const rootCount = ref(0);
const refreshing = ref(false); // 刷新状态

// 任务管理相关
const showTaskDialog = ref(false);
const isDragOver = ref(false);
const refreshingTasks = ref(false);
const currentPath = ref("/"); // 当前路径，用于文件上传
const taskUpdateTrigger = ref(0); // 用于触发任务列表更新的响应式变量

// 离线下载相关
const showOfflineDownloadDialog = ref(false);
const submittingOfflineDownload = ref(false);
const offlineDownloadForm = ref({
  url: "",
  filename: "",
  path: "/",
});
const directoryOptions = ref([{ label: "根目录", value: "/" }]);

function toggleLeftDrawer() {
  leftDrawerOpen.value = !leftDrawerOpen.value;
}

watch(isLogin, (newLoginStatus) => {
  if (newLoginStatus) {
    showLoginDialog.value = false;
  } else {
    showLoginDialog.value = true;
  }
});

// 任务相关计算属性
const allTasks = computed(() => {
  taskUpdateTrigger.value; // 依赖响应式变量
  const tasks = taskQueue.getAllTasks();
  console.log("计算属性 allTasks 更新:", tasks.length, "个任务");
  return tasks;
});
const taskStats = computed(() => {
  taskUpdateTrigger.value; // 依赖响应式变量
  const stats = taskQueue.getStats();
  console.log("计算属性 taskStats 更新:", stats);
  return stats;
});
const activeTaskCount = computed(
  () => taskStats.value.running + taskStats.value.pending
);

function formatSize(size) {
  if (size < 1024) {
    return size + "B";
  } else if (size < 1024 * 1024) {
    return (size / 1024).toFixed(2) + "KB";
  } else if (size < 1024 * 1024 * 1024) {
    return (size / 1024 / 1024).toFixed(2) + "MB";
  } else {
    return (size / 1024 / 1024 / 1024).toFixed(2) + "GB";
  }
}

// 检查登录状态的函数
function checkLoginStatus() {
  if (!isLogin.value) {
    showLoginDialog.value = true;
    return false;
  }
  return true;
}

// 处理侧边栏项目点击
function handleItemClick() {
  if (!checkLoginStatus()) {
    return;
  }
  // 这里可以添加具体的功能逻辑
  console.log("用户已登录，可以执行操作");
}

// 处理离线下载
function handleOfflineDownload() {
  if (!checkLoginStatus()) {
    return;
  }

  // 重置表单
  offlineDownloadForm.value = {
    url: "",
    filename: "",
    path: currentPath.value,
  };

  // 更新目录选项
  updateDirectoryOptions();

  showOfflineDownloadDialog.value = true;
}

// 更新目录选项
function updateDirectoryOptions() {
  const options = [{ label: "根目录", value: "/" }];

  // 如果有目录数据，添加所有目录
  if (directoryData.value) {
    const addDirectories = (items, parentPath = "") => {
      items.forEach((item) => {
        if (item.file_type === "directory") {
          const fullPath = parentPath + "/" + item.filename;
          options.push({
            label: item.filename,
            value: fullPath,
          });

          // 递归添加子目录
          if (item.items && item.items.length > 0) {
            addDirectories(item.items, fullPath);
          }
        }
      });
    };

    addDirectories(directoryData.value);
  }

  directoryOptions.value = options;
}

// 提交离线下载
async function submitOfflineDownload() {
  if (!offlineDownloadForm.value.url) {
    $q.notify({
      type: "warning",
      message: "请输入文件URL",
      position: "top",
    });
    return;
  }

  try {
    submittingOfflineDownload.value = true;

    // 从URL中提取文件名（如果用户没有输入）
    let finalFilename = offlineDownloadForm.value.filename;
    if (!finalFilename) {
      try {
        const urlObj = new URL(offlineDownloadForm.value.url);
        const pathname = urlObj.pathname;
        finalFilename = pathname.split("/").pop() || "downloaded_file";
      } catch (error) {
        finalFilename = "downloaded_file";
      }
    }

    // 添加到任务队列
    taskQueue.addTask(TaskType.OFFLINE_DOWNLOAD, {
      url: offlineDownloadForm.value.url,
      path: offlineDownloadForm.value.path,
      filename: finalFilename,
    });

    // 成功通知
    $q.notify({
      type: "positive",
      message: `已添加离线下载任务到队列`,
      position: "top",
      timeout: 3000,
    });

    // 关闭对话框
    showOfflineDownloadDialog.value = false;
  } catch (error) {
    console.error("添加离线下载任务失败:", error);
    $q.notify({
      type: "negative",
      message: "添加离线下载任务失败: " + (error.message || "未知错误"),
      position: "top",
      timeout: 3000,
    });
  } finally {
    submittingOfflineDownload.value = false;
  }
}

// 任务管理相关方法
function getTaskIcon(type) {
  const icons = {
    [TaskType.DOWNLOAD]: "download",
    [TaskType.UPLOAD]: "cloud_upload",
    [TaskType.DELETE]: "delete",
    [TaskType.RENAME]: "edit",
    [TaskType.CREATE_FOLDER]: "create_new_folder",
    [TaskType.MOVE]: "drive_file_move",
    [TaskType.COPY]: "file_copy",
    [TaskType.OFFLINE_DOWNLOAD]: "cloud_download",
  };
  return icons[type] || "help";
}

function getTaskColor(status) {
  const colors = {
    [TaskStatus.PENDING]: "grey",
    [TaskStatus.RUNNING]: "primary",
    [TaskStatus.COMPLETED]: "green",
    [TaskStatus.FAILED]: "red",
    [TaskStatus.CANCELLED]: "orange",
    [TaskStatus.PAUSED]: "orange",
  };
  return colors[status] || "grey";
}

function getTaskTitle(task) {
  const titles = {
    [TaskType.DOWNLOAD]: "下载文件",
    [TaskType.UPLOAD]: "上传文件",
    [TaskType.DELETE]: "删除文件",
    [TaskType.RENAME]: "重命名",
    [TaskType.CREATE_FOLDER]: "创建文件夹",
    [TaskType.MOVE]: "移动文件",
    [TaskType.COPY]: "复制文件",
    [TaskType.OFFLINE_DOWNLOAD]: "离线下载",
  };
  return titles[task.type] || "未知任务";
}

function getTaskDescription(task) {
  switch (task.type) {
    case TaskType.DOWNLOAD:
      return `下载: ${task.data.fileName || "未知文件"}`;
    case TaskType.UPLOAD:
      return `上传: ${task.data.file?.name || "未知文件"} 到 ${
        task.data.targetPath || "/"
      }`;
    case TaskType.DELETE:
      return `删除: ${task.data.filePath || "未知文件"}`;
    case TaskType.RENAME:
      return `重命名: ${task.data.oldPath || "未知文件"}`;
    case TaskType.CREATE_FOLDER:
      return `创建文件夹: ${task.data.folderName || "未知文件夹"}`;
    case TaskType.MOVE:
      return `移动: ${task.data.sourcePath || "未知文件"}`;
    case TaskType.COPY:
      return `复制: ${task.data.sourcePath || "未知文件"}`;
    case TaskType.OFFLINE_DOWNLOAD:
      return `离线下载: ${task.data.filename || "未知文件"} 到 ${
        task.data.path || "/"
      }`;
    default:
      return "未知任务";
  }
}

function getStatusText(status) {
  const statusTexts = {
    [TaskStatus.PENDING]: "等待中",
    [TaskStatus.RUNNING]: "运行中",
    [TaskStatus.COMPLETED]: "已完成",
    [TaskStatus.FAILED]: "失败",
    [TaskStatus.CANCELLED]: "已取消",
    [TaskStatus.PAUSED]: "已暂停",
  };
  return statusTexts[status] || "未知状态";
}

function formatTime(date) {
  if (!date) return "";
  const now = new Date();
  const diff = now - new Date(date);
  const minutes = Math.floor(diff / 60000);
  const hours = Math.floor(diff / 3600000);
  const days = Math.floor(diff / 86400000);

  if (days > 0) return `${days}天前`;
  if (hours > 0) return `${hours}小时前`;
  if (minutes > 0) return `${minutes}分钟前`;
  return "刚刚";
}

// 任务操作方法
function pauseTask(taskId) {
  taskQueue.pauseTask(taskId);
}

function resumeTask(taskId) {
  taskQueue.resumeTask(taskId);
}

function retryTask(taskId) {
  taskQueue.retryTask(taskId);
}

function cancelTask(taskId) {
  taskQueue.cancelTask(taskId);
}

function removeTask(taskId) {
  taskQueue.removeTask(taskId);
}

function refreshTasks() {
  refreshingTasks.value = true;
  setTimeout(() => {
    refreshingTasks.value = false;
  }, 500);
}

function clearCompletedTasks() {
  taskQueue.clearCompletedTasks();
}

// 更新当前路径
function updateCurrentPath(path) {
  currentPath.value = path;
  // 更新目录选项
  updateDirectoryOptions();
}

// 文件拖拽上传处理
function handleFileDrop(event) {
  event.preventDefault();
  isDragOver.value = false;

  if (!checkLoginStatus()) {
    return;
  }

  const files = Array.from(event.dataTransfer.files);
  if (files.length === 0) return;

  // 为每个文件创建上传任务
  files.forEach((file) => {
    taskQueue.addTask(TaskType.UPLOAD, {
      file: file,
      targetPath: currentPath.value,
    });
  });

  $q.notify({
    type: "positive",
    message: `已添加 ${files.length} 个上传任务`,
    position: "top",
    timeout: 2000,
  });
}

// 处理添加按钮点击
function handleAddClick() {
  if (!checkLoginStatus()) {
    return;
  }
  // 这里可以添加具体的功能逻辑
  console.log("用户已登录，可以执行添加操作");
}

// 跳转到登录页面
function goToLogin() {
  showLoginDialog.value = false;
  // 跳转到登录页面
  const encode = encodeURIComponent;
  window.location.href = `https://login.zhuchundashuaige.com/#/?RedirectUri=${encode(
    "http://" + window.location.host
  )}&Type=SPA`;
}

// 跳转到个人资料页面
function goToProfile() {
  window.open("https://login.zhuchundashuaige.com/", "_blank");
}

// 跳转到设置页面
function goToSettings() {
  $q.notify({
    type: "info",
    message: "设置功能开发中...",
  });
}

// 搜索功能
function performSearch() {
  if (!searchText.value.trim()) {
    $q.notify({
      type: "warning",
      message: "请输入搜索关键词",
      position: "top",
    });
    return;
  }

  // 跳转到搜索页面
  router.push({
    path: "/search",
    query: { keyword: searchText.value.trim() },
  });
}

// 导航功能
function goToHome() {
  router.push("/");
}

function goToCategory(type) {
  if (!checkLoginStatus()) {
    return;
  }
  router.push(`/category/${type}`);
}

// 刷新数据
async function refreshData() {
  if (!checkLoginStatus()) {
    return;
  }

  // 防止重复点击
  if (refreshing.value) {
    return;
  }

  try {
    refreshing.value = true;
    console.log("开始刷新数据");
    const data = await browseDirectory("/");
    directoryData.value = data.items;
    rootSize.value = data.total_size;
    rootCount.value = data.total_count;
    console.log("刷新数据成功:", data);

    $q.notify({
      type: "positive",
      message: "数据刷新成功",
      position: "top",
      timeout: 2000,
    });
  } catch (error) {
    console.error("刷新数据失败:", error);
    $q.notify({
      type: "negative",
      message: "刷新失败: " + (error.message || "未知错误"),
      position: "top",
      timeout: 3000,
    });
  } finally {
    refreshing.value = false;
  }
}

// 处理登出
function handleLogout() {
  $q.dialog({
    title: "确认退出",
    message: "确定要退出登录吗？",
    cancel: true,
    persistent: true,
  }).onOk(() => {
    // 清除登录信息
    localStorage.removeItem("token");
    localStorage.removeItem("email");
    localStorage.removeItem("rememberMe");

    // 重置登录状态
    isLogin.value = false;

    $q.notify({
      type: "positive",
      message: "已成功退出登录",
    });
  });
}

onMounted(async () => {
  // 启动任务队列
  taskQueue.start();

  // 监听任务队列事件，触发UI更新
  const updateTaskList = (task) => {
    console.log("任务状态更新:", task?.id, task?.status, task?.type);
    taskUpdateTrigger.value++;
  };

  // 注册事件监听器
  const events = [
    "taskAdded",
    "taskStarted",
    "taskCompleted",
    "taskFailed",
    "taskCancelled",
    "taskPaused",
    "taskResumed",
    "taskRetried",
    "taskRemoved",
    "tasksCleared",
  ];

  events.forEach((event) => {
    taskQueue.on(event, updateTaskList);
  });

  console.log("任务队列事件监听器已注册");

  onLoggedIn(async () => {
    // 获取资源列表
    $q.loading.show();
    console.log("用户已登录，可以加载数据");
    try {
      const data = await browseDirectory("/");
      directoryData.value = data.items;
      rootSize.value = data.total_size;
      rootCount.value = data.total_count;
      console.log("获取目录数据成功:", data);

      // 更新目录选项
      updateDirectoryOptions();
    } catch (error) {
      console.error("获取目录数据失败:", error);
    } finally {
      $q.loading.hide();
    }
  });

  // 添加键盘快捷键支持
  const handleKeyDown = (event) => {
    // F5键刷新
    if (event.key === "F5") {
      event.preventDefault();
      refreshData();
    }
  };

  window.addEventListener("keydown", handleKeyDown);

  // 清理事件监听器
  return () => {
    window.removeEventListener("keydown", handleKeyDown);
    // 移除任务队列事件监听器
    events.forEach((event) => {
      taskQueue.off(event, updateTaskList);
    });
    console.log("任务队列事件监听器已清理");
  };
});
</script>

<style scoped>
.folder-card:hover {
  transform: translateY(-2px);
  transition: transform 0.2s ease;
}

/* 任务对话框样式 */
.task-dialog {
  max-width: 100%;
  max-height: 100%;
}

.stat-card {
  min-width: 120px;
}

.upload-drop-zone {
  border: 2px dashed #e0e0e0;
  border-radius: 8px;
  background-color: #fafafa;
  transition: all 0.3s ease;
  cursor: pointer;
}

.upload-drop-zone:hover {
  border-color: #1976d2;
  background-color: #f5f5f5;
}

.upload-drop-zone.drag-over {
  border-color: #1976d2;
  background-color: #e3f2fd;
}

.task-item {
  transition: background-color 0.2s ease;
}

.task-item:hover {
  background-color: #f5f5f5;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .stat-card {
    min-width: 80px;
  }

  .upload-drop-zone {
    padding: 1rem !important;
  }
}
</style>
